//
//  BaseWebViewController.swift
//  Edaixi-iOS
//
//  Created by 刘树华 on 2017/12/4.
//  Copyright © 2017年 刘树华. All rights reserved.
//

import Foundation
import UIKit
import WebKit
class BaseWebViewController: BaseViewController,WKNavigationDelegate{
    
    var web :WKWebView!
    
    private var pro : ProgressView!
    override func viewDidLoad() {
        super.viewDidLoad()
     
       let config = WKWebViewConfiguration()
        config.userContentController = WKUserContentController()
        web = WKWebView(frame:  contentRect(), configuration: config)
        web.navigationDelegate = self
        web.addObserver(self, forKeyPath: "estimatedProgress", options: NSKeyValueObservingOptions.new.union(.old), context: nil)
        
        view.addSubview(web)
        pro = ProgressView(backColor: UIColor.white, fillColor: UIColor.cyan)
        pro.frame = CGRect(x: 0, y: contentRect().origin.y, width: SCREEN_WIDTH, height: 2)
//        pro.setPro(pro: 0.8)
        view.layer.addSublayer(pro)
        if let request = loadRequest() {
            web.load(request)
        }
        
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        guard let changeValue = change else {
            return
        }
        if let old = changeValue[NSKeyValueChangeKey.oldKey] ,let new = changeValue[NSKeyValueChangeKey.newKey]  {
            
//            let arr : [String]? = toArr(data: old)
            if let newValue = new as? CGFloat , let oldValue = old as? CGFloat {
                if newValue > oldValue {
                    pro.setPro(pro: newValue)
                }
            }
        }
    }
    
    
    func loadRequest() -> URLRequest? {
        return nil
    }
    /*
     配置完之后，在js界面中调用方法：window.webkit.messageHandlers.<name>.postMessage(<messageBody>) 就可以将js页面内容发送webview中。
     <name>就是添加的对象的名称FirstJsObect。<messageBody>传递的消息。
    */
    func JSInvokeWebView(script:WeakWKScriptMessage,name:String)  {
        web.configuration.userContentController.add(script, name: name)
    }
    
    func webViewInvokeJS(jsStr:String,complte: @escaping ((Any?,Error?)->())) {
        web.evaluateJavaScript(jsStr, completionHandler: complte)
    }
    
//MARK ---WEBView WKNavigationDelegate
    
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        MYDebugPrintf(msg: "开始加载")
    }
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        MYDebugPrintf(msg: "开始接收主要内容")
    }
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        MYDebugPrintf(msg: "页面加载完成")
    }
    
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        MYDebugPrintf(msg: "页面加载失败")
    }
    func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
        MYDebugPrintf(msg: "页面重定向")
    }
//    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
//        MYDebugPrintf(msg: "在请求开始加载之前调用，决定是否跳转")
//    }
//    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
//        MYDebugPrintf(msg: "在收到响应开始加载后，决定是否跳转")
//    }
    
    deinit {
        MYDebugPrintf(msg: "父类webVC析构")
        web.removeObserver(self, forKeyPath: "estimatedProgress")
//       web.configuration.userContentController.removeScriptMessageHandler(forName: "")
    }
    
}

class WeakWKScriptMessage: NSObject , WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        
    }
}

